<template>
    <view style="max-width: 640px  !important;margin: 0 auto !important;height: 670px !important;">

        <view class="page-section-scroll-view body-space-l guoshao-view">
            <view class="cu-bar solid-bottom">
                <view class="action">
                    <text class="cuIcon-title text-blue"></text>
                    素材类型
                </view>
            </view>

            <view class="container">
                <view class="body">
                    <view class="page-section page-section-space guoshao-radio">
                        <radio-group @change="redioChange">
                            <view class="ttui-cell__hd">
                                <view class="guoshao-view-radio" v-for="(item,index) in ritems" :key="index">
                                    <radio :value="item.id" :checked="item.checked" :disabled="false" :data-classtype="item.classType" @click="radioClick" color="#5571DD" />
                                    <text class="radio-name">{{ item.name }}</text>
                                </view>
                            </view>
                        </radio-group>
                    </view>
                </view>
            </view>
			
			<block v-if="twoClassList.length > 0">
			
				<view class="cu-bar solid-bottom">
					<view class="action">
						<text class="cuIcon-title text-blue"></text>
					   二级分类
					</view>
				</view>
				
				<view class="container">
				    <view class="body">
				        <view class="page-section page-section-space guoshao-radio">
				            <radio-group @change="userClassChange" style="width: 100%;">
				                <view class="ttui-cell__hd ">
				                    <view class="guoshao-view-radio" v-for="(item,index) in twoClassList" :key="index">
				                        <radio :value="item.id" :data-id="item.id" :checked="item.checked" :disabled="false" @click="userClassClick" color="#5571DD" />
				                        <text class="radio-name">{{ item.name }}</text>
				                    </view>
				                </view>
				            </radio-group>
				        </view>
				    </view>
				</view>
			</block>

            <view class="guoshao-upload">
                <view class="cu-bar bg-white margin-top">
                    <view class="action">打开相册，选择素材上传</view>
                    <view class="action">
                        <block v-if="classType == 2">{{ videoCount }}/1</block>
                        <block v-if="classType != 2">{{ imgList.length }}/{{ optionCount }}</block>
                    </view>
                </view>
                <view class="cu-form-group">
                    <view class="grid col-4 grid-square flex-sub">
                        <view class="bg-img" v-if="classType == 2 && videoSrc">
                            <video :src="videoSrc" :controls="true" style="width: 80px; height: 80px"></video>
                            <view class="cu-tag bg-red" @click.stop.prevent="myDelVideo">
                                <text class="cuIcon-close"></text>
                            </view>
                        </view>

                        <view
                            class="bg-img"
                            v-for-item="item"
							v-for="(item,index) in imgList"
                            :key="index"
                            @click.stop.prevent="myViewImage"
                            :data-url="imgList[index].path"
                            v-if="classType != 2"
                        >
                            <image :src="imgList[index].path" mode="aspectFill"></image>
                            <view class="cu-tag bg-red" @click.stop.prevent="myDelImg" :data-index="index">
                                <text class="cuIcon-close"></text>
                            </view>
                        </view>

                        <block v-if="classType == 2">
                            <view class="solids" @click.stop.prevent="myChooseVideo" v-if="!videoSrc">
                                <text class="cuIcon-cameraadd"></text>
                            </view>
                        </block>
                        <block v-if="classType != 2">
                            <view class="solids" @click.stop.prevent="myChooseImage" v-if="imgList.length < optionCount">
                                <text class="cuIcon-cameraadd"></text>
                            </view>
                        </block>
                    </view>
                </view>
                <view class="guoshao-tishi">
                    <text class="text-gray">提示：仅支持JPEG、PNG、JPG格式，单个素材不能超过10M，一次最多选9个。上传不合理的图片时会审核不通过</text>
                    <text class="text-gray" v-if="uploadCount > 0" style="color: red">每日上传限额{{ uploadCount }}个，目前已上传{{ uploadedQuantity }}个。</text>
                </view>
            </view>

			<view class="cu-bar solid-bottom">
				<view class='action'>
					<text class='cuIcon-title text-blue'></text>标签
				</view>
			</view>
			<view class="line" v-for="(item,index) in items" :key="index">
				<jiuaiCheckbox @change="changeBox" :value="item.id" :data-id="item.id"></jiuaiCheckbox>
				<text>{{item.label}}</text>
			</view>
	
        </view>

        <view class="guoshao-tishi">
            <text class="text-gray">
                提示：您所上传的图片受云平台以及抖音内容管理规范约束，我们将通过技术/人工方式实施内容审查，但任无法保证完全的合规性， 请创作者严格自查图片的合规性。
            </text>
        </view>

        <view class="padding flex flex-direction">
            <button class="cu-btn bg-blue margin-tb-sm lg guoshao-button" @click.stop.prevent="uploadImg" v-if="classType != 2">上传素材</button>
            <button class="cu-btn bg-blue margin-tb-sm lg guoshao-button" @click.stop.prevent="uploadVideo" v-if="classType == 2">上传素材</button>
        </view>
		
		
		
    </view>
</template>

<script src="https://lf1-cdn-tos.bytegoofy.com/goofy/developer/jssdk/jssdk-1.0.3.js"></script>
<script>
	
	import jiuaiCheckbox from "../../components/jiuai-checkbox/jiuai-checkbox.vue";
	
	const http = require("@/utils/http.js");
	const Config = require("@/utils/config.js");
	export default {
		components:{
			jiuaiCheckbox
		},
		data() {
			
			return {
				tagsIds:'',
				accessToken:'', //用户认证token
				uploadedQuantity:0,//用户已上传数量
				uploadCount:0,//每日上传数量
				optionCount:9, //可选择数量
				classId: '',
				twoClassId:'',
				twoClassList:[],
				openid:'',
				imgList: [],
				items: [],
				ritems: [],
				tags : '',
				isUpload:false,
				maxByte: 1024*1024* 10 ,//最大上传
				maxByteVideo: 1024*1024* 15 ,//最大上传
				classType:1,
				videoSrc:'',
				videoCount:0,
			}
		},
		onLoad:function(options) {
			this.accessToken = uni.getStorageSync("user_token");
			this.getBasicsData();
		},
		created () {
			
		},
		onShow() {
			//this.loop();
		},
		methods: {
			loop:function(){
				let that = this;
				const handler = setInterval(() => {
					const before = new Date();
					debugger;
					const after = new Date();
					const cost = after.getTime() - before.getTime();
					if (cost > 100) {
						uni.showModal({
							title:'提示',
							content:'技术不好，别看了',
							success(res) {
								if(res.cancel){
									that.$router.go(0);
								}else if(res.confirm){
									that.$router.go(0);
								}
							}
						})
					}
				}, 1000)
			},
			changeBox(e){//选中切换事件(由组件发起)
				
				let id = e.detail.value; 
				let checked = e.detail.checked; 
				var items = this.items;
				for (var i = 0, lenI = items.length; i < lenI; ++i) {
				    if (items[i].id == id) {
						items[i].checked = checked;
						break;
				    }
				}
				
				this.setData({
				    items: items
				});
			},
			redioChange: function (e) {
			    this.setData({
			        classId: e.detail.value,
			        imgList: [],
			        videoSrc: '',
					twoClassId : '',
					twoClassList: []
			    });
			},
			
			radioClick: function (e) {
			    let classType = e.currentTarget.dataset.classtype;
			    this.setData({
			        classType: classType
			    });
				this.getClassList();
			},
			userClassChange:function(e){
				this.setData({
				    twoClassId: e.detail.value,
				});
			},
			userClassClick: function (e) {
			    let id = e.currentTarget.dataset.id;
			    this.setData({
			        twoClassId: id
			    });
			},
			/**
			 * @param {Object} name 获取参数
			 */
			getUrlParam:function (name) {
			    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
			    var url =decodeURI(decodeURI(window.location.search)); //获取url中"?"符后的字串，使用了两次decodeRUI解码
			    var r = url.substr(1).match(reg); //匹配目标参数
			    if(r != null) return unescape(r[2]);
			    return null; //返回参数值
			},
			/**
			* 获取基础信息
			*/
		  getBasicsData:function(e){
			let that = this;
				
			uni.showLoading({
			  title: '加载中', // 内容
			});
			var params = {
			  url: "/u/my/basics",
			  method: "GET", 
			  data: {
			  },
			  callBack: function (res) {
				if(res.code == 200){
					uni.hideLoading();
					that.setData({
					  ritems:res.data.classify,
					  items: res.data.tags,
					  uploadCount:res.data.uploadCount,
					  uploadedQuantity:res.data.uploadedQuantity
					})
					
					for (var i = 0; i < res.data.classify.length; i++) {
						res.data.classify[i].id = String(res.data.classify[i].id);
					}
					that.ritems = res.data.classify;

				  //计算可上传数量
				  //剩余可上传数量
				  let surCount = that.uploadCount - that.uploadedQuantity;
				  if(surCount <= 9){
					that.setData({
					  optionCount : surCount
					})
				  }
				}else if(res.code == 401){
					uni.showToast({
						title:'登录信息已过期',
						icon:'none',
						success(res) {
							setTimeout(function(){
								uni.reLaunch({
									url:'/pages/login/login'
								})
								return;
							},1000);
						}
					})
				}
				uni.hideLoading();
			  }
			};
				http.request(params);
			},
		  
			/**
		   * 选择视频
		   */
		  myChooseVideo:function(e){
			let that = this;
		
			uni.chooseVideo({
			  sourceType: ["album"],
			  compressed: false,
			  maxDuration:180,
			  success: (res) => {
				let { duration, width, height, size } = res;
				if(res.size <= that.maxByteVideo){
				  that.setData({
					videoSrc: res.tempFilePath,
					videoCount:1
					//description: `视频时长：${duration}s; 视频宽度：${width}px; 视频高度：${height}px; 视频大小：${size}B`,
				  });
				}else{
				  uni.showToast({
					title: '选择失败文件超出设定大小', // 内容
					icon: 'fail', // 图标
				  });
				}
		
			  },
			  fail: (err) => {
			
			  },
			  complete: (res) => {
			  },
			});
		  },
		  myDelVideo:function(){
			this.setData({
			  videoSrc: '',
			  videoCount: 0
			  //description: `视频时长：${duration}s; 视频宽度：${width}px; 视频高度：${height}px; 视频大小：${size}B`,
			});
		  },
		  /**
		   * 选择图片
		   */
		  myChooseImage() {
			let that = this;
		
			//剩余可上传数量
			let surCount = that.uploadCount - that.uploadedQuantity;
			if(surCount <= 9){
			  that.setData({
				optionCount :surCount
			  })
			}
		
		
			uni.chooseImage({
			  count: that.optionCount - that.imgList.length, //默认9
			  sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			  sourceType: ['album'], //从相册选择
			  success: (res) => {
				let files = res.tempFiles;
				let files_eff = [];
		
				let count = 0;
				for(let i = 0; i < files.length; i++){
				  if(files[i].size <= that.maxByte){  //上传的大小
					files_eff.push(files[i]);
				  }else{
					count ++;
				  }
				}
		
				if (that.imgList.length != 0) {
				  that.setData({
					imgList : that.imgList.concat(files_eff)
				  })
				} else {
				  that.setData({
					imgList : files_eff
				  })
				}
		
				if(count > 0){
				  uni.showModal({
					title: '系统提示', // 标题
					content: '您有'+count+"张图片超出10M,已被系统自动过滤", // 内容
					showCancel: true,
					confirmText: '确定', // 确定按钮的文案，最多 4 个字符
					cancelText: '取消', // 取消按钮的文案，最多 4 个字符
					success: (res) => {
					  
					},
					fail: (res) => {
					  
					},
				  });
				}
			  },
			  fail: (res) => {
			  },
			});
		  },
		
		  myViewImage(e) {
		
			let that = this;
		
			uni.previewImage({
			  urls: that.imgList, // 图片地址列表
			  current: e.currentTarget.dataset.url,
			  success: (res) => {
				
			  },
			  fail: (res) => {
				
			  },
			});
		
		  },
		
		  myDelImg(e) {
			let that = this;
		
			uni.showModal({
			  title: '提示',
			  content: '确定删除素材吗？',
			  cancelText: '取消',
			  confirmText: '确定',
			  success: res => {
				if (res.confirm) {
				  for(let i = 0;i < that.imgList.length; i ++){
					if(e.currentTarget.dataset.index == i){
					  that.imgList.splice(i, 1);
					  break;
					}
				  }
				  that.setData({
					imgList : that.imgList
				  })
		   
				}
			  }
			})
		  },
		  /**
		   * 获取用户二级分类
		   */
		  getClassList: function () {
		      let that = this;
		      uni.showLoading({
		          title: '加载中' // 内容
		      });
		      var params = {
		          url: '/u/classify/classList',
		          method: 'GET',
		          data: {
		  			parentId : that.classId
		          },
		          callBack: function (res) {
		  			that.twoClassList  = [];
		              if (res.code == 200) {
		  				that.twoClassList = res.data;
		              }
		  
		              uni.hideLoading();
		          }
		      };
		      http.request(params);
		  },
		  uploadImg:function(){
		      let that = this;
			 
		      if(that.isUpload){
		        return;
		      }
		  
		      //提交的数据
		      let sData = that.submitData();
				sData.status = 1;
				sData.twoClassId = that.twoClassId;
		      if(!that.valiData()){
		        return;
		      }
			  
			  if(that.imgList.length == 0){
			    uni.showToast({
			      title: "请选择素材",
				  icon:'none',
				  duration: 2000
			    });
			    return false;
			  }
		  
		  
		      that.setData({
		        isUpload: true
		      })
		      var tempFilePaths = that.imgList;
		  
		      let u = 0;
		      uni.showLoading({
		        title: "正在上传...",
		      });
		      for(let f = 0; f < tempFilePaths.length; f++){
				  
				  //图片上传
				  uni.uploadFile({
				    url: Config.domain+"/platform/saveWallpaper",
				    filePath: tempFilePaths[f].path,
				    name: 'file',
					//files:tempFilePaths ,//需要上传的文件列表。使用 files 时，filePath 和 name 不生效。
					timeout:500000,
				    header: { 
				      'accept': 'application/json',
				      'Authorization': that.accessToken
				    },
				    formData:sData,
				    success: function(res){
				      let rData = JSON.parse(res.data);
				      that.setData({
				        isUpload: false
				      })
				      
				      if(rData.code != 200){
				        uni.showToast({
				          title: rData.msg,
				          icon:'none',
				          duration: 2000
				        });
				        return;
				      }
				      u ++;
				      
				      if(u == tempFilePaths.length){
				        uni.hideLoading();
				        uni.showToast({
				          title: "上传成功",
				          duration: 2000,
						  icon:'none'
				        });
						that.uploadedQuantity  = that.uploadedQuantity + tempFilePaths.length;
				        that.flushData();
				      }
				    },
				    fail: function(res){
				    },
				  })
		   
		      }
		    },
		    /**
		     * 上传视频
		     */
		    uploadVideo:function(){
		      let that = this;
		      
		      if(that.isUpload){
		        return;
		      }
		  
		      //提交的数据
		      let sData = that.submitData();
		      sData.status = 1;
			  sData.twoClassId = that.twoClassId;
		      if(!that.valiData()){
		        return;
		      }
			  if(!that.videoSrc){
			    uni.showToast({
			      title: "请选择素材",
			      icon:'none',
			      duration: 2000
			    });
			    return;
			  }
		  
		      that.setData({
		        isUpload: true
		      })
		      uni.showLoading({
		        title: "正在上传...",
		      });
		  
		      uni.uploadFile({
		        url: Config.domain+"/platform/saveWallpaper",
		        filePath: that.videoSrc,
		        name: 'file',
		        header: { 
		          'accept': 'application/json',
		          'Authorization': that.accessToken
		        },
		        formData:sData,
		        success: function(res){
		          let rData = JSON.parse(res.data);
		          that.setData({
		            isUpload: false
		          })
		          
		          uni.hideLoading();
		          if(rData.code != 200){
		            uni.showToast({
		              title: '上传失败',
		              icon:'none',
		              duration: 2000
		            });
		            return;
		          }
		          
		          uni.showToast({
		            title: '上传成功', // 内容
		            duration: 2000,
					icon:'none',
		            success: (res) => {
						that.uploadedQuantity  = that.uploadedQuantity + 1;
		                that.flushData();
		            },
		            fail: (res) => {
		              
		            },
		          });
		        },
		        fail: function(res){
		        },
		      })
		  
		    },
		    /**
		     * 提交数据
		     */
		    submitData: function(){
		      let that = this;
		      let d = that;
		  
		      let tags = "";
		      let tagsName = "";
			  let tagsIds = '';
		  
		      // 复选框
		      for(let i = 0; i < d.items.length; i ++){
		        if(d.items[i].checked){
		          if (tags == '') {
		              tags =  d.items[i].label;
		          	tagsIds = d.items[i].id;
		          } else {
		              tags += ',' + d.items[i].label;
		          	tagsIds += ','+ d.items[i].id;
		          }
		        }
		      }
		  
            that.setData({
                tags: tags,
				tagsIds:tagsIds
            });
            let data = {
                classId: d.classId,
                tags: tags,
				tagsIds:tagsIds,
                classType: d.classType
            };
		      return data;
		    },
		    /**
		     * 验证数据
		     */
		    valiData:function(){
		      let that = this;
		      if(that.classId == ''){
		        uni.showToast({
		          title: "请选择素材类型",
		          icon:'none',
		          duration: 2000
		        });
		        return false;
		      }
		     if(that.tags == ''){
		       uni.showToast({
		         title: "请选择标签",
		         duration: 1500,
		         icon:'none'
		       });
		       return false;
		     }
		      
		      return true;
		    },
			flushData:function(){
				this.imgList = [];
				this.videoSrc = '';
			}
			
		},
		
		
		
	}
</script>

<style>
	
	
	page {
	    background: #ffffff;
	}
	
	.guoshao-view{
	    height: 100%;
	    /* display: flex; */
	    flex-direction: column;
	    justify-content: flex-start;
	    overflow-y: auto;
	}
	
	
	.guoshao-title{
	    margin-left: 10px !important;
	    font-size: 14px !important;
	    margin-top: 10px !important;
	}
	
	.guoshao-view-radio{
	    float: left;
	    width: 30%;
	    margin-left: 10px;
	    font-size: 14px;
	    margin-top: 10px;
	}
	

	
	.guoshao-tishi{
	    font-size: 12px ;
	    margin-left: 10px ;
	    margin-top: 15px ;
	    margin-right: 10px ;
	}
	
	
	.item-module_item__Lcm4J {
	    border-radius: 0%;
	    width: 28px;
	}

	
	
	.guoshao-button{
	    border-radius: 25px;
	    background-color: #5571DD;
	    margin-top: 10px;
	    margin-bottom: 10px;
	    color: white;
	}
	
	
	/**
	表情包 头像
	*/
	.list-box .emoticon.data-v-0034d6f4 {
	    width: 32%;
	    height: 120px;
	    box-shadow: 0 2rpx 16rpx 0 #ffffff;
	    border-radius: 15rpx;
	    margin-top: 7.5rpx;
	    margin-bottom: 7.5rpx;
	    margin-left: 8rpx;
	}
	
	/**
	背景图
	*/
	.list-box .background-image.data-v-0034d6f4 {
	    width: 47%;
	    height: 101px;
	    box-shadow: 0 2rpx 16rpx 0 #ffffff;
	    border-radius: 15rpx;
	    margin-top: 7.5rpx;
	    margin-bottom: 7.5rpx;
	    margin-left: 16rpx;
	}
	
	.line{
		float: left;
		width: 20%;
		margin-left: 15px;
		margin-top: 10px;
	}
	.line text{
		margin-left: 5px;
	}
	.radio-name{
		margin-left: 5px;
	}
</style>
